<script setup>
import {ref, computed, onMounted} from "vue";
import TitleComponent from "@/components/TitleComponent.vue";
import router from "@/router/index.js";
import {queryQuestionsList} from "@/api/question.js";
import {Message} from "@arco-design/web-vue";
import {saveAnswer} from "@/api/answer.js";

// 题目数据
const questionData = ref({
  total: 0,
  id: "",
  appId: "",
  appName: "",
  scoringStrategy: "",
  userId: "",
  questionsList: []
});

// 当前题目索引
const currentQuestionIndex = ref(0);

// 用户答案
const userAnswers = ref([]);

// 是否显示提交确认对话框
const showSubmitDialog = ref(false);

// 是否已提交
const isSubmitted = ref(false);

// 获取路由参数ID
const id = ref(0);

const questionLoading = ref(false);

const submitLoading = ref(false);
// 计算当前题目
const currentQuestion = computed(() => {
  if (questionData.value.questionsList.length > 0 && currentQuestionIndex.value < questionData.value.questionsList.length) {
    return questionData.value.questionsList[currentQuestionIndex.value];
  }
  return null;
});

// 获取题目列表
const getQuestionList = async () => {
  id.value = router.currentRoute.value.params.id;
  questionLoading.value = true;
  try {
    const res = await queryQuestionsList(id.value);
    if (res.data.code === 1) {
      questionData.value.total = Number(res.data.data.total);
      questionData.value.id = res.data.data.id;
      questionData.value.appId = res.data.data.appId;
      questionData.value.appName = res.data.data.appName;
      questionData.value.scoringStrategy = res.data.data.scoringStrategy;
      questionData.value.userId = res.data.data.userId;
      questionData.value.questionsList = res.data.data.list;
      // 初始化用户答案数组
      userAnswers.value = new Array(questionData.value.questionsList.length).fill(null);
    } else {
      Message.error('获取题目失败,无法进行答题');
      router.back();
    }
  } catch (err) {
    console.log(err);
  } finally {
    questionLoading.value = false;
  }
};

// 跳转到指定题目
const goToQuestion = (index) => {
  if (index >= 0 && index < questionData.value.questionsList.length) {
    currentQuestionIndex.value = index;
  }
};

// 上一题
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
  }
};

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questionData.value.questionsList.length - 1) {
    currentQuestionIndex.value++;
  }
};

// 检查是否所有题目都已回答
const allQuestionsAnswered = computed(() => {
  return userAnswers.value.every(answer => answer !== null);
});

// 提交答案
const submitAnswers = () => {
  if (!allQuestionsAnswered.value) {
    Message.warning('请回答所有题目后再提交');
    return;
  }
  if (questionData.value.questionsList.length <= 0) {
    Message.warning('题目列表为空，无法答题');
    return;
  }
  showSubmitDialog.value = true;
};

// 确认提交
const confirmSubmit = async () => {
  try {
    submitLoading.value = true;
    isSubmitted.value = true;
    if (questionData.value.scoringStrategy === 1) {
      Message.info('AI判题需要一定时间，请耐心等待')
    }
    const formData = {
      questionId: questionData.value.id,
      appId: questionData.value.appId,
      answerList: userAnswers.value
    };
    const res = await saveAnswer(formData);
    if (res.data.code === 1) {
      Message.success('提交成功');
      const resultId = res.data.data;
      router.push(`/answer/result/${resultId}`);
    } else {
      Message.error('提交失败');
    }
  } catch (error) {
    console.log(error);
  } finally {
    showSubmitDialog.value = false;
    submitLoading.value  = false;
  }
};

// 取消提交
const cancelSubmit = () => {
  showSubmitDialog.value = false;
};

// 组件挂载时获取题目列表
onMounted(() => {
  getQuestionList();
});
</script>

<template>
  <div id="answer-page">
    <a-card class="card">
      <title-component :title-text="questionData.appName"></title-component>
      <div class="answer-container">
        <!-- 导航栏 -->
        <div class="question-nav nav-top nav-left">
          <div class="nav-title">题目导航</div>
          <div class="nav-buttons">
            <a-button
              v-for="(_, index) in questionData.questionsList"
              :key="index"
              :type="currentQuestionIndex === index? 'primary' : (userAnswers[index]? 'outline' :'secondary')"
              :status="userAnswers[index]? 'success' : ''"
              @click="goToQuestion(index)"
              class="nav-button"
            >
              {{ index + 1 }}
            </a-button>
          </div>
          <a-button type="primary" long @click="submitAnswers" :disabled="isSubmitted" :loading="submitLoading">
            提交答案
          </a-button>
        </div>

        <!-- 答题区域 -->
        <div class="question-content">
          <div v-if="questionData.questionsList.length && !questionLoading" class="question-area">
            <div class="question-title">
              <span class="question-number">{{ currentQuestionIndex + 1 }}.</span>
              {{ currentQuestion.title }}
            </div>

            <div class="options-list">
              <a-radio-group v-model="userAnswers[currentQuestionIndex]" direction="vertical">
                <a-radio
                  v-for="option in currentQuestion.options"
                  :key="option.key"
                  :value="option.key"
                  :disabled="isSubmitted"
                >
                  <span class="option-key">{{ option.key }}.</span>
                  <span class="option-value">{{ option.value }}</span>
                </a-radio>
              </a-radio-group>
            </div>

            <div class="navigation-buttons">
              <a-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">
                <template #icon>
                  <icon-left/>
                </template>
                上一题
              </a-button>
              <a-button @click="nextQuestion"
                        :disabled="currentQuestionIndex === questionData.questionsList.length - 1">
                下一题
                <template #icon>
                  <icon-right/>
                </template>
              </a-button>
            </div>
          </div>
          <div v-else-if="questionLoading" class="loading-area">
            <a-spin/>
            <p>加载题目中...</p>
          </div>
          <div v-if="questionData.questionsList.length <= 0 && !questionLoading " class="empty-state">
            <p>该应用暂无题目</p>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 提交确认对话框 -->
    <a-modal
      v-model:visible="showSubmitDialog"
      @cancel="cancelSubmit"
      @ok="confirmSubmit"
      :ok-loading="submitLoading"
      title="确认提交"
      :width="300"
    >
      <p>确定要提交答案吗？提交后将无法修改。</p>
    </a-modal>
  </div>
</template>

<style scoped>
.card {
  margin: 20px 0;
}

.answer-container {
  display: flex;
  margin-top: 20px;
}

.nav-left {
  width: 200px;
  margin-right: 20px;
}

@media (max-width: 768px) {
  .answer-container {
    flex-direction: column;
  }

  .nav-left {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }
}

.question-nav {
  background-color: var(--color-fill-2);
  padding: 15px;
  border-radius: 4px;
}

.nav-title {
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.nav-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
  justify-content: center;
}

.nav-button {
  width: 36px;
  height: 36px;
  padding: 0;
}

.question-content {
  flex: 1;
  background-color: var(--color-fill-2);
  padding: 20px;
  border-radius: 4px;
}

.question-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
}

.question-number {
  font-weight: bold;
  margin-right: 8px;
}

.options-list {
  margin-bottom: 30px;
}

.option-key {
  font-weight: bold;
  margin-right: 8px;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.loading-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}
</style>
